<template>
  <div class="order-page">
    <a-page-header title="订单管理" sub-title="查看和管理所有订单" />
    
    <a-card class="card-shadow">
      <!-- 搜索筛选 -->
      <a-form layout="inline" class="search-form">
        <a-form-item label="订单号">
          <a-input v-model:value="searchForm.orderNo" placeholder="请输入订单号" style="width: 200px;" />
        </a-form-item>
        
        <a-form-item label="科目">
          <a-input v-model:value="searchForm.subject" placeholder="请输入科目" style="width: 150px;" />
        </a-form-item>
        
        <a-form-item label="状态">
          <a-select v-model:value="searchForm.status" style="width: 120px;" placeholder="全部">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="CREATED">待支付</a-select-option>
            <a-select-option value="PAID">已支付</a-select-option>
            <a-select-option value="IN_PROGRESS">进行中</a-select-option>
            <a-select-option value="COMPLETED">已完成</a-select-option>
            <a-select-option value="CANCELLED">已取消</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
      
      <!-- 标签页 -->
      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange" class="order-tabs">
        <a-tab-pane key="" tab="全部订单" />
        <a-tab-pane key="CREATED" tab="待支付" />
        <a-tab-pane key="PAID" tab="已支付" />
        <a-tab-pane key="IN_PROGRESS" tab="进行中" />
        <a-tab-pane key="COMPLETED" tab="已完成" />
        <a-tab-pane key="CANCELLED" tab="已取消" />
      </a-tabs>
      
      <!-- 订单表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderNo'">
            <a-typography-text copyable>{{ record.orderNo }}</a-typography-text>
          </template>
          
          <template v-else-if="column.key === 'amount'">
            <span style="color: #52c41a; font-weight: bold;">¥{{ record.totalAmount }}</span>
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.statusText }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewDetail(record)">
                详情
              </a-button>
              <a-dropdown>
                <a-button type="link" size="small">
                  更多 <down-outlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleUpdateStatus(record)">
                      <edit-outlined />
                      修改状态
                    </a-menu-item>
                    <a-menu-item danger @click="handleDelete(record)">
                      <delete-outlined />
                      删除订单
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 订单详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="订单详情"
      width="700px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="订单号" :span="2">{{ currentOrder.orderNo }}</a-descriptions-item>
        <a-descriptions-item label="家长">{{ currentOrder.parentName }}</a-descriptions-item>
        <a-descriptions-item label="教员">{{ currentOrder.teacherName }}</a-descriptions-item>
        <a-descriptions-item label="科目">{{ currentOrder.subject }}</a-descriptions-item>
        <a-descriptions-item label="年级">{{ currentOrder.grade || '-' }}</a-descriptions-item>
        <a-descriptions-item label="授课方式">{{ getTeachingTypeText(currentOrder.teachingType) }}</a-descriptions-item>
        <a-descriptions-item label="总课时">{{ currentOrder.totalHours }}小时</a-descriptions-item>
        <a-descriptions-item label="时薪">¥{{ currentOrder.hourlyRate }}/时</a-descriptions-item>
        <a-descriptions-item label="订单金额">¥{{ currentOrder.totalAmount }}</a-descriptions-item>
        <a-descriptions-item label="订单状态">
          <a-tag :color="getStatusColor(currentOrder.status)">
            {{ currentOrder.statusText }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间" :span="2">{{ currentOrder.createdAt }}</a-descriptions-item>
        <a-descriptions-item label="上课地址" :span="2" v-if="currentOrder.address">
          {{ currentOrder.address }}
        </a-descriptions-item>
        <a-descriptions-item label="特殊要求" :span="2" v-if="currentOrder.requirements">
          {{ currentOrder.requirements }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
    
    <!-- 修改状态弹窗 -->
    <a-modal
      v-model:open="statusModalVisible"
      title="修改订单状态"
      @ok="handleStatusSubmit"
    >
      <a-form :model="statusForm" :label-col="{ span: 6 }">
        <a-form-item label="订单号">
          <a-input v-model:value="statusForm.orderNo" disabled />
        </a-form-item>
        
        <a-form-item label="当前状态">
          <a-tag :color="getStatusColor(statusForm.oldStatus)">
            {{ getStatusText(statusForm.oldStatus) }}
          </a-tag>
        </a-form-item>
        
        <a-form-item label="新状态" required>
          <a-select v-model:value="statusForm.newStatus">
            <a-select-option value="CREATED">待支付</a-select-option>
            <a-select-option value="PAID">已支付</a-select-option>
            <a-select-option value="IN_PROGRESS">进行中</a-select-option>
            <a-select-option value="COMPLETED">已完成</a-select-option>
            <a-select-option value="CANCELLED">已取消</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="备注">
          <a-textarea v-model:value="statusForm.remark" :rows="3" placeholder="请输入修改原因" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { 
  SearchOutlined, 
  DownOutlined, 
  EditOutlined, 
  DeleteOutlined 
} from '@ant-design/icons-vue'
import { getAdminOrderList, updateOrderStatus, deleteOrder } from '@/api/order'

const loading = ref(false)
const activeTab = ref('')
const detailModalVisible = ref(false)
const statusModalVisible = ref(false)

const searchForm = reactive({
  orderNo: '',
  subject: '',
  status: ''
})

const statusForm = reactive({
  orderId: null,
  orderNo: '',
  oldStatus: '',
  newStatus: '',
  remark: ''
})

const currentOrder = ref({})

const columns = [
  { title: '订单号', key: 'orderNo', width: 200 },
  { title: '家长', dataIndex: 'parentName', key: 'parentName', width: 100 },
  { title: '教员', dataIndex: 'teacherName', key: 'teacherName', width: 100 },
  { title: '科目', dataIndex: 'subject', key: 'subject', width: 100 },
  { title: '课时', dataIndex: 'totalHours', key: 'totalHours', width: 80 },
  { title: '金额', key: 'amount', width: 100 },
  { title: '状态', key: 'status', width: 100 },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 180 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
]

const dataSource = ref([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`
})

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  
  try {
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    
    if (activeTab.value) {
      params.status = activeTab.value
    }
    
    const res = await getAdminOrderList(params)
    
    if (res.data) {
      dataSource.value = res.data.list || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    message.error(error.message || '加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadOrders()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    subject: '',
    status: ''
  })
  pagination.current = 1
  loadOrders()
}

// 标签页切换
const handleTabChange = (key) => {
  searchForm.status = key
  pagination.current = 1
  loadOrders()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadOrders()
}

// 查看详情
const handleViewDetail = (record) => {
  currentOrder.value = record
  detailModalVisible.value = true
}

// 修改状态
const handleUpdateStatus = (record) => {
  statusForm.orderId = record.id
  statusForm.orderNo = record.orderNo
  statusForm.oldStatus = record.status
  statusForm.newStatus = record.status
  statusForm.remark = ''
  statusModalVisible.value = true
}

// 提交状态修改
const handleStatusSubmit = async () => {
  if (!statusForm.newStatus) {
    message.error('请选择新状态')
    return
  }
  
  try {
    await updateOrderStatus(statusForm.orderId, {
      status: statusForm.newStatus,
      remark: statusForm.remark
    })
    
    message.success('状态更新成功')
    statusModalVisible.value = false
    loadOrders()
  } catch (error) {
    message.error(error.message || '状态更新失败')
  }
}

// 删除订单
const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除订单 ${record.orderNo} 吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      try {
        await deleteOrder(record.id)
        message.success('删除成功')
        loadOrders()
      } catch (error) {
        message.error(error.message || '删除失败')
      }
    }
  })
}

// 状态相关方法
const getStatusColor = (status) => {
  const colorMap = {
    CREATED: 'orange',
    PAID: 'blue',
    IN_PROGRESS: 'cyan',
    COMPLETED: 'green',
    CANCELLED: 'default',
    REFUNDED: 'red'
  }
  return colorMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    CREATED: '待支付',
    PAID: '已支付',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
    REFUNDED: '已退款'
  }
  return textMap[status] || status
}

const getTeachingTypeText = (type) => {
  const typeMap = {
    ONLINE: '线上授课',
    OFFLINE: '线下授课',
    BOTH: '线上/线下均可'
  }
  return typeMap[type] || type
}

onMounted(() => {
  loadOrders()
})
</script>

<style lang="scss" scoped>
.order-page {
  .search-form {
    margin-bottom: 24px;
    padding-bottom: 24px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .order-tabs {
    margin-top: 16px;
  }
}
</style>
